package view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.widget.ListView;
import android.widget.Scroller;

public class MyDiyListView extends ListView{

	private String TAG = MyDiyListView.class.getSimpleName();
	
	
	private static final int TOUCH_STATE_REST = 0;
	private static final int TOUCH_STATE_SCROLLING = 1;
	private static final int SNAP_VELOCITY = 600;
	private int mTouchState = TOUCH_STATE_REST;
	private int mTouchSlop;
	private float mLastMotionX;
	private float mLastMotionY;
	
	
	VelocityTracker mVelocityTracker;
	Scroller mScroller;
	
	public MyDiyListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		
		mScroller = new Scroller(context);
		
		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
		
	}
	
	
	@Override
	protected void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();
	}
	
	@Override
	protected void onDetachedFromWindow() {
		// TODO Auto-generated method stub
		super.onDetachedFromWindow();
	}
	

	
	  //调用此方法滚动到目标位置  
    public void SmoothScrollTo(int fx, int fy) {  
        int dx = fx - mScroller.getFinalX();  
        int dy = fy - mScroller.getFinalY();  
        smoothScrollBy(dx, dy);  
    }  
  
    //调用此方法设置滚动的相对偏移  
    public void SmoothScrollBy(int dx, int dy) {  
  
        //设置mScroller的滚动偏移量  
        mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy);  
        invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用，否则不一定会刷新界面，看不到滚动效果  
    } 
    
    
     
	// 由父视图调用用来请求子视图根据偏移值 mScrollX,mScrollY重新绘制  
    @Override  
    public void computeScroll() {     
        // TODO Auto-generated method stub  
        Log.d(TAG, "computeScroll");  
        // 如果返回true，表示动画还没有结束  
        // 因为前面startScroll，所以只有在startScroll完成时 才会为false  
        if (mScroller.computeScrollOffset()) {  
            Log.d(TAG, mScroller.getCurrX() + "======" + mScroller.getCurrY());  
            // 产生了动画效果，根据当前值 每次滚动一点  
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());  
              
            Log.d(TAG, "### getleft is " + getLeft() + " ### getRight is " + getRight());  
            //此时同样也需要刷新View ，否则效果可能有误差  
            postInvalidate();  
        }  
        else  
            Log.i(TAG, "have done the scoller -----");  
    }  
    
	
	///*
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		Log.e(TAG, "onInterceptTouchEvent-slop:" + mTouchSlop);
		final int action = ev.getAction();
		if ((action == MotionEvent.ACTION_MOVE)
				&& (mTouchState != TOUCH_STATE_REST)) {
			return true;
		}
		final float x = ev.getX();
		final float y = ev.getY();
		switch (action) {
		case MotionEvent.ACTION_MOVE:
			final int xDiff = (int) Math.abs(mLastMotionX - x);
			if (xDiff > mTouchSlop) {
				mTouchState = TOUCH_STATE_SCROLLING;
			}
			break;
		case MotionEvent.ACTION_DOWN:
			mLastMotionX = x;
			mLastMotionY = y;
			
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
					: TOUCH_STATE_SCROLLING;
			
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		
		Log.e(TAG, "onInterceptTouchEvent-mTouchState:" + mTouchState);
		
		return true; //mTouchState != TOUCH_STATE_REST;
	}
	//*/
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.e(TAG, "onTouchEvent");
		
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
		final int action = event.getAction();
		final float x = event.getX();
		final float y = event.getY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			Log.e(TAG, "event down!");
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
			mLastMotionX = x;
			mLastMotionY = y;
			
			break;
		case MotionEvent.ACTION_MOVE:{
			int deltaX = (int) (mLastMotionX - x);
			int deltaY = (int) (mLastMotionY - y);
			if( Math.abs(deltaY) > 100 )
				break;
			mLastMotionY = y;
			mLastMotionX = x;
			//SmoothScrollBy(0, deltaY); //
			scrollBy(0, deltaY);
			break;
		}
		case MotionEvent.ACTION_UP:
			Log.e(TAG, "event : up");
			 //if (mTouchState == TOUCH_STATE_SCROLLING) 
			 {
				final VelocityTracker velocityTracker = mVelocityTracker;
				velocityTracker.computeCurrentVelocity(1000);
				int velocityX = (int) velocityTracker.getXVelocity();
				int velocityY = (int) velocityTracker.getYVelocity();
				Log.e(TAG, "velocityX:" + velocityX);
				Log.e(TAG, "velocityY:" + velocityY);
				
				int deltaX = (int) (mLastMotionX - x);
				int deltaY = (int) (mLastMotionY - y);
				
				/*
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						scrollTo(0, 0); //SmoothScrollTo(0, 0);
					}
				}, 1000);
				*/
				
				scrollTo(0, 0);
				
				
				
				/*
				if (velocityX > SNAP_VELOCITY && mCurScreen > 0) {
					// Fling enough to move left
					//Log.e(TAG, "snap left");
				} else if (velocityX < -SNAP_VELOCITY
						&& mCurScreen < getChildCount() - 1) {
					// Fling enough to move right
					//Log.e(TAG, "snap right");
				} else {
					
				}
				*/
				
				if (mVelocityTracker != null) {
					mVelocityTracker.recycle();
					mVelocityTracker = null;
				}
			}
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return true;
	}
	
	
	
}
